package com.atguigu.dwm.common.util;

import org.apache.hadoop.hive.ql.lib.DefaultGraphWalker;
import org.apache.hadoop.hive.ql.lib.Dispatcher;
import org.apache.hadoop.hive.ql.lib.Node;
import org.apache.hadoop.hive.ql.parse.ASTNode;
import org.apache.hadoop.hive.ql.parse.ParseDriver;
import org.apache.hadoop.hive.ql.parse.ParseException;
import org.apache.hadoop.hive.ql.parse.SemanticException;

import java.util.Collections;
import java.util.Stack;

public class SqlParser {


    public  static void parse(String sql, Dispatcher dispatcher) throws  Exception {
     //1    构建语法树工具对象
        ParseDriver parseDriver = new ParseDriver();

     //2   把sql放入语法树工具 进行解析 ->语法树
        ASTNode astNode = parseDriver.parse(sql);
        //向下移动一个节点作为遍历起始节点
        astNode= (ASTNode) astNode.getChild(0);
      //3    对语法树进行遍历
        DefaultGraphWalker defaultGraphWalker = new DefaultGraphWalker(dispatcher);

      //4   在遍历过程中提取需要的元素
        defaultGraphWalker.startWalking(Collections.singletonList(astNode),null  );


    }

    public static void main(String[] args) throws Exception {
        String sql="  with t1 as (select aa(a),b,c,dt as dd from tt1,  tt2 \n" +
                "             where tt1.a=tt2.b and dt='2023-05-11'  )\n" +
                "  insert overwrite table tt9  \n" +
                "  select a,b,c \n" +
                "  from t1 \n" +
                "  where    dt = date_add('${xxx}',-4 )    \n" +
                "  union \n" +
                "  select a,b,c \n" +
                "  from t2\n" +
                "   where    dt = date_add('${xxx} ',-7 )   ";
        SourceTableDispatcher dispatcher = new SourceTableDispatcher();
        dispatcher.setDefaultSchemaName("gmall");
        SqlParser.parse(sql,dispatcher);
        System.out.println("dispatcher = " + dispatcher);

    }
    public static class TestDispatcher implements Dispatcher {

        @Override
        public Object dispatch(Node nd, Stack<Node> stack, Object... nodeOutputs) throws SemanticException {
            ASTNode astNode = (ASTNode) nd;
            System.out.println("到达node: " +astNode.getText() );
            return null;
        }
    }
}
